home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 8713 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  67 lines

  1. Path: thor.tu.hac.com!collins
  2. From: collins@thor.tu.hac.com (Ron Collins)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: revised code of calling a function twice from printf
  5. Date: 6 Mar 1996 00:32:08 GMT
  6. Organization: Advanced Depot Systems
  7. Message-ID: <4hime8$hh5@hacgate2.hac.com>
  8. References: <4hfs54$k4e@newsbf02.news.aol.com>
  9. NNTP-Posting-Host: thor.tu.hac.com
  10. X-Newsreader: TIN [version 1.2 PL2]
  11.  
  12. Razine (razine@aol.com) wrote:
  13. : Here is the actual code , modified with everyone's suggestions.  However
  14. : there is still a bug in here somewhere.  Can anyone please explain what is
  15. : wrong with this.
  16.  
  17. : It returns 
  18.  
  19. : [1] NONE       [2] NE
  20.  
  21. : I would like it to return
  22.  
  23. : [1] NONE       [2] Asprin
  24.  
  25. : Thank you very much for your help.  it is greatly appreciated.
  26.  
  27.  
  28. : #include <stdio.h>
  29. : #include <string.h>
  30.  
  31. : char *display_drug_type(int drug_index);
  32.  
  33. : int drug_inventory[5]={0,1,0,0,0};
  34.  
  35. : int main() {
  36.  
  37. :     printf("[1] %s             [2] %s  
  38. : \n",display_drug_type(0),display_drug_type(1));
  39.  
  40. : return 0;
  41. :         }
  42.  
  43. : char *display_drug_type(int drug_index) {
  44. :    char drug_type[81]="\0";
  45.  
  46. :    switch(drug_inventory[drug_index]) {
  47. :      case 0 : strcpy(drug_type,"NONE"); break;
  48. :      case 1 : strcpy(drug_type,"Asprin"); break;
  49. :      default : printf("Error in Display_drug_inventory");
  50. :                         }
  51. :    return drug_type;
  52. : }
  53.  
  54. It ain't gonna happen.
  55.  
  56. Mainly, because array "drug_type" is transient; that is, the array 
  57. "disappears" in between calls to "display_drug_type", which means that
  58. the "char *" you are returning from the function call is meaningless.
  59.  
  60. You might consider using a "static" array to maintain a valid "char *",
  61. but this would obviously be incorrect also (for your purposes).
  62.  
  63.  
  64.             -- collins --
  65.  
  66.  
  67.